package com.wl.spring.mvc.web;

import com.wl.spring.mvc.entity.Result;
import com.wl.spring.mvc.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.File;
import java.io.IOException;

//Controller   默认当前对象所有的方法返回的是视图名
//RestController   默认....是json数据

@Controller
public class IndexController {

    @GetMapping("toTest")
    public String ToTest(String name, HttpServletRequest request) {
        System.out.println("=========ToTest=======");
       request.setAttribute("name",name);
       User user = new User();
       user.setName(name);
       request.getSession().setAttribute("myinfo",user);
        return "test.jsp";
    }

    @GetMapping("myinfo")
    @ResponseBody
    public User myinfo(@SessionAttribute User myinfo){
        return myinfo;
    }

    @RequestMapping("reg")
    @ResponseBody
    public Result reg(@Valid User user, Errors errors) {
        if (errors.hasErrors()) {
            return new Result(0, "验证错误",
                        errors.getAllErrors());
        }else {
            return new Result(1,"验证成功",
                    null);
        }
    }

    @PostMapping  ("upload")    //GetMapping 不支持提交请求体
    @ResponseBody
                                        //表示将head接收过来，然后把head映射到file对象里面去
    public Result uploadHead(@RequestParam("head") MultipartFile file,User user) throws IOException {
        //获取上传的文件名
        String filename = file.getOriginalFilename();
        file.transferTo(new File("D:\\三期课程视频\\SpringMVC2 控制和返回" + filename) );
        return new Result(1,"文件上传成功",user);
    }
}
